//
//  SEHospitalizeHeaderItem.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import UIKit

enum SEHospitalizeHeaderItemType {
    case online, community, outpatient // 线上问诊、社区检查、门诊预约
}

typealias SEHospitalizeHeaderItemClosure = (SEHospitalizeHeaderItemType, Bool) -> Void

@IBDesignable class SEHospitalizeHeaderItem: UIView {
    
    var itemTapClosure: SEHospitalizeHeaderItemClosure?

    var view: UIView!
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descLabel: UILabel!
    
    // MARK: - IBInspectable
    
    @IBInspectable var image: UIImage? {
        get { imageView.image }
        set { imageView.image = newValue }
    }
    
    @IBInspectable var title: String? {
        get { titleLabel.text }
        set {
            titleLabel.text = newValue
            _itemType(with: newValue)
        }
    }
    
    @IBInspectable var desc: String? {
        get { descLabel.text }
        set { descLabel.text = newValue }
    }
    
    @IBInspectable var titleColor: UIColor {
        get { titleLabel.textColor }
        set { titleLabel.textColor = newValue }
    }
    
    @IBInspectable var descColor: UIColor {
        get { descLabel.textColor }
        set { descLabel.textColor = newValue }
    }
    
    private var _itemType = SEHospitalizeHeaderItemType.online
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        view = loadViewFromNib()
        
        view.setLayerCorners(rect: view.bounds, radius: 10)
        view.setShadow()
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(_tapToPush))
        view.addGestureRecognizer(tapGesture)
    }
    
    @objc private func _tapToPush() {
        itemTapClosure?(_itemType, true)
    }
    
    private func _itemType(with title: String?) {
        if title == "线上问诊" {
            _itemType = .online
        } else if title == "社区检查" {
            _itemType = .community
        } else {
            _itemType = .outpatient
        }
    }
    
    func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName(), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(view)

        return view
    }

    private func nibName() -> String {
        return String(describing: type(of: self))
    }

}
